package Z11_3_moreLock;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author： pang-yun
 * @date： 2021-11-03 13:12
 * 功能目的 ：用于  死锁
 */

public class DeadLock {
    public static void main(String[] args) {
        ChopsLick a = new ChopsLick("1");
        ChopsLick b = new ChopsLick("2");
        ChopsLick c = new ChopsLick("3");
        ChopsLick d = new ChopsLick("4");
        ChopsLick e = new ChopsLick("5");

        new Philosophy("AA",a,b).start();
        new Philosophy("BB",b,c).start();
        new Philosophy("CC",c,d).start();
        new Philosophy("DD",d,e).start();
        new Philosophy("EE",e,a).start();
    }

}


@Slf4j
@Data
@AllArgsConstructor
class Philosophy extends Thread{

    ChopsLick left;
    ChopsLick right;

    public Philosophy(String name,ChopsLick left, ChopsLick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true){
            synchronized (left){
                synchronized (right){
                    eat();
                }
            }
        }
    }

    public void eat(){
        log.info("eat!");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Data
@AllArgsConstructor
class ChopsLick{
    private String name;
}
